'''续上一题，找另外一个网站，尝试编程提取一些自己感兴趣的东西出来。（提示：可以自行搜索用于HTML解析的第三方库）'''
def askFileName():
    print('{:*^50}'.format('本程序用于抓取微博网页内的文本内容')+'\n')
    print('注意事项：请把在浏览器中Ctrl+S将网页保存，模式选择“整个网页”，\n    并将.HTML文件放到本程序同一目录下\n')
    fileName = input('请输入你要打开的文件名（包括后缀）：')
    return fileName

def readFile(fileName:'str'):
    f = open(fileName,'r',encoding = 'utf-8')
    htmlList = f.readlines()
    f.close()
    print('文件已读取完成！')
    return htmlList

def getTopLine(htmlList):
    topLine = 0
    for line in htmlList:
        topLine += 1
        if 'class="icon-top"' in line:
            break
        else:
            continue   
    print('置顶热搜在第{}行'.format(topLine))
    return topLine

def getRankLines(htmlList):
    rankLine = 0
    rankLines = []
    for line in htmlList:
        rankLine += 1
        if 'class="td-01 ranktop"' in line:
            rankLines.append(rankLine)
            print('已检索到第{}条热搜'.format(len(rankLines)))
        else:
            continue
    #print(rankLines)
    return rankLines

def getTopEvent(htmlList,topLine):
    nameLine,iconLine = htmlList[topLine+1],htmlList[topLine+3]
    url = 'https://s.weibo.com' + nameLine.split('"')[1]
    name = nameLine.split('>')[1].split('<')[0]
    veiw = 'unknown'
    icon = iconLine.split('>')[2].split('<')[0]
    topEvent = [url,name,veiw,icon]
    return  topEvent

def getRankEvents(htmlList,rankLines):
    rankEvents = []
    for i in rankLines:
        nameLine = htmlList[i+1]
        #print(nameLine)
        url = 'https://s.weibo.com' + nameLine.split('"')[1]
        name = nameLine.split('>')[1].split('<')[0]
        if '<span>' in htmlList[i+2]:
            veiwLine = htmlList[i+2]
            veiw = veiwLine.split('>')[1].split('<')[0]
            if 'class="icon-txt"' in htmlList[i+4]:
                iconLine = htmlList[i+4]
                icon = iconLine.split('>')[2].split('<')[0]
            else:
                icon = 'null'
        else:
            veiw = 'unknown'
            icon = 'null'
        event = [url,name,veiw,icon]
        rankEvents.append(event)
    return rankEvents      

def writeTxt(fileName,topEvent,rankEvents):
    rankEvents.append(topEvent)
    print('共{}条热搜'.format(len(rankEvents)))
    f = open(fileName.strip('.html')+'.txt','w',encoding='utf-8')
    i = 0
    for event in rankEvents:
        line = ''
        for item in event:
            line = line + str(item) + '\t'
        line=  line.strip('\t') + '\n'
        #print(line)
        f.write(line)
        i += 1
        print('已写入{}条热搜'.format(i))
    print('新文件已写入完毕！')
    f.close()

def main():
    fileName = askFileName()
    htmlList = readFile(fileName)
    topLine  = getTopLine(htmlList)
    rankLines = getRankLines(htmlList)
    topEvent = getTopEvent(htmlList,topLine)
    rankEvents = getRankEvents(htmlList,rankLines)
    writeTxt(fileName,topEvent,rankEvents)

main()
    
    
    

